package com.otdemo.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.otdemo.dao.RestUserDao;
import com.otdemo.entity.RestUser;
import com.otdemo.resp.ResultResponse;
import com.otdemo.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Objects;

@WebServlet("/rest/user/validate")
public class ValidateController extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//request和response的编码方法设置，一律UTF-8
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
//		1.获取前端的参数
        BufferedReader reader = req.getReader();
        String s = reader.readLine();
        RestUser rest = new ObjectMapper().readValue(s, RestUser.class);
//      2.去后台查询数据,看有没有这一条数据，有就返回数据，否则返回空
        RestUser user1 = new RestUserDao().findByUserName(rest.getUsername());
        if (Objects.isNull(user1)) {
            resp.getWriter().write("<script>alert('账号不存在');</script>");
        }
        if (!rest.getPassword().equals(user1.getPassword())) {
            resp.getWriter().write("<script>alert('密码不正确');</script>");
        }
        user1.setPassword(null);
        HttpSession session = req.getSession();
        session.setAttribute(Constants.CURRENT_USER, user1);
        ResultResponse resultResponse = new ResultResponse();
        resp.getWriter().write(new ObjectMapper().writeValueAsString(resultResponse.success()));
//		3.根据判断，做出不同的相应
//        req.getRequestDispatcher("User.jsp").forward(req, resp);
    }
}
